﻿using Minecraft.Config;
using Minecraft.Config.Csv.CsvCls;
using Minecraft.Model;
using Minecraft.Model.Backpack;
using Minecraft.Model.ReqResp;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Minecraft.ServerHall.Cmd
{
	public class EquipmentGoodsUnsnatch : CommandBase<MinecraftSession, StringRequestInfo>
	{
		public override string Name
		{
			get
			{
				return ProtocolHelper.GetProtocolStr(defCommand);
			}
		}
		private EnumCommand defCommand = EnumCommand.Equipment_EquipmentGoodsUnsnatch;
		public override void ExecuteCommand(MinecraftSession session, StringRequestInfo requestInfo)
		{
			var req = requestInfo.GetRequestObj<EquipmentGoodsUnsnatchReq>(session);
			if (req == null)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误1：（原因：请求实体为空）" });
				return;
			}
			if (!session.minecraftSessionInfo.IsLogin)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误1：（原因：未登录）" });
				return;
			}

			//if (JsonConfig.Value.IsDebug)
			//{
			//	req.goodsId = (from info in session.minecraftSessionInfo.goodsList
			//				   where (info.enumGoodsBelongsToType_Convert == EnumGoodsBelongsToType.Equipment)
			//				   select info).ToList().FirstOrDefault().GoodsId;
			//	req.enumEquipmentGoodsUnsnatchMode = EnumEquipmentGoodsUnsnatchMode.Drag;
			//	req.enumGoodsBelongsToType = EnumGoodsBelongsToType.Backpack;

			//	//加载背包物品goodsItem信息
			//	List<BackpackGoodsItemInfo> goodsItemInfoList2 = session.GetBackpackGoodsItemInfoList();

			//	req.targetGoodsPosition = (from info in goodsItemInfoList2
			//							   where info.enumGoodsBelongsToType == req.enumGoodsBelongsToType && info.GoodsNum <= 0
			//							   select info).ToList().FirstOrDefault().GoodsPosition;

			//}
			//物品目的地判断
			if (!MinecraftConfig.bpShortbarBelongsToTypeList.Any(m => m == req.enumGoodsBelongsToTypeTarget))
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：物品目的地不正确，前端传入的物品目的地为【{req.enumGoodsBelongsToTypeTarget.ToString()}】）" });
				return;
			}
			//装备类型判断
			if (!MinecraftConfig.equipmentBelongsToTypeList.Any(m => m == req.enumGoodsBelongsToTypeSource))
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：装备类型不正确，前端传入的装备类型为【{req.enumGoodsBelongsToTypeTarget.ToString()}】）" });
				return;
			}
			if (req.GoodsPositionSource < 0)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误4：（原因：GoodsPositionSource < 0）" });
				return;
			}
			if (req.GoodsPositionTarget < 0)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误5：（原因：GoodsPositionTarget < 0）" });
				return;
			}
			if (req.guid.IsNullOrWhiteSpace())
			{
				req.guid = "";
			}

			//暂时写死
			if (req.enumGoodsBelongsToTypeSource == EnumGoodsBelongsToType.SurvivorEquipment)
			{
				req.guid = session.minecraftSessionInfo.survivorList.FirstOrDefault(m => m.PlayerId == session.minecraftSessionInfo.player.PlayerId).SurvivorId;
			}

			//switch (req.enumEquipmentGoodsUnsnatchMode)
			//{
			//	case EnumEquipmentGoodsUnsnatchMode.Click:
			//		break;
			//	case EnumEquipmentGoodsUnsnatchMode.Drag:
			//		{
						var baseResp2 = req.enumGoodsBelongsToTypeTarget.GetBackpackGoodsBelongsToTypeBaseType(req.GoodsPositionTarget, session, "EquipmentGoodsUnsnatch", req.guid);
						if (baseResp2.RespLevel != RespLevelEnum.Success)
						{
							session.Send(defCommand, req, baseResp2);
							return;
						}
			//		}
			//		break;
			//	default:
			//		{
			//			session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误1：（原因：装备物品卸下方式 不存在）" });
			//			return;
			//		}
			//}
			var equipmentInfo = session.minecraftSessionInfo.goodsList.FirstOrDefault(m => m.enumGoodsBelongsToType_Convert == req.enumGoodsBelongsToTypeSource && m.GoodsPosition == req.GoodsPositionSource && m.guid == req.guid);
			if (equipmentInfo == null)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误1：（原因：装备中不存在该物品）" });
				return;
			}
			//Mod_Items mod_Items = CsvConfig.itemsList.FirstOrDefault(m => m.Id == equipmentInfo.GoodsItemId);
			Mod_Items mod_Items = CsvConfig.GetMod_ItemsInfoById(equipmentInfo.GoodsItemId);
			if (mod_Items == null)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误1：（原因：物品表中不存在该物品）" });
				return;
			}
			if (mod_Items.enumGoodsType_Convert != EnumGoodsType.Equipment)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误1：（原因：该物品不属于装备，无法卸下，出现这个原因可能是在装备穿戴时就出现了问题）" });
				return;
			}

			//从配置中读取指定物品存放数量上限
			var goodsItemMaxNum = session.GetMaxCellNumConvert(equipmentInfo.GoodsItemId);
			//加载背包物品goodsItem信息
			List<BackpackGoodsItemInfo> goodsItemInfoList = session.GetBackpackGoodsItemInfoList(req.enumGoodsBelongsToTypeTarget, req.guid, out BaseResp baseResp);
			if (baseResp.RespLevel != RespLevelEnum.Success)
			{
				session.Send(defCommand, req, baseResp);
				return;
			}

			Func<BackpackGoodsItemInfo, bool> predicate = null;
			//switch (req.enumEquipmentGoodsUnsnatchMode)
			//{
			//	case EnumEquipmentGoodsUnsnatchMode.Click:
			//		{
			//			predicate = m => (m.GoodsNum <= 0 || m.GoodsItemId == equipmentInfo.GoodsItemId && m.GoodsNum < goodsItemMaxNum) && m.guid == req.guid;
			//		}
			//		break;
			//	case EnumEquipmentGoodsUnsnatchMode.Drag:
			//		{
						predicate = m => (m.enumGoodsBelongsToType == req.enumGoodsBelongsToTypeTarget && m.GoodsPosition == req.GoodsPositionTarget && m.GoodsNum <= 0) && m.guid == req.guid;
			//		}
			//		break;
			//}
			if (predicate == null)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误1：（原因：服务器错误，predicate 为空）" });
				return;
			}
			//找到背包可以放置的格子信息
			var canCareGoodsInfo = goodsItemInfoList.FirstOrDefault(predicate);
			if (canCareGoodsInfo == null)
			{
				session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = "错误9（原因：格子已经满了，或者不符合卸载条件，装备无法卸载）" });
				return;
			}
			EnumAttribute enumAttribute = mod_Items.modAttributeInfo_Convert.enumAttribute;
			int attributeAfterVal = 0;
			switch (mod_Items.modAttributeInfo_Convert.enumAttribute)
			{
				case EnumAttribute.Def:
					{
						switch (req.enumGoodsBelongsToTypeSource)
						{

							case EnumGoodsBelongsToType.Equipment:
								{
									session.minecraftSessionInfo.player.Fight_Defense -= mod_Items.modAttributeInfo_Convert.Value;
									if (session.minecraftSessionInfo.player.Fight_Defense < 0)
									{
										session.minecraftSessionInfo.player.Fight_Defense = 0;
									}
									attributeAfterVal = session.minecraftSessionInfo.player.Fight_Defense;
								}
								break;
							case EnumGoodsBelongsToType.SurvivorEquipment:
								{
									//幸存者装备
								}
								break;
							default:
								break;
						}


					}
					break;
				case EnumAttribute.BagSize:
					{
						switch (req.enumGoodsBelongsToTypeSource)
						{

							case EnumGoodsBelongsToType.Equipment:
								{
									session.minecraftSessionInfo.BackpackCellNum -= mod_Items.modAttributeInfo_Convert.Value;
									if (session.minecraftSessionInfo.BackpackCellNum < MinecraftConfig.BackpackCellInitNum)
									{
										session.minecraftSessionInfo.BackpackCellNum = MinecraftConfig.BackpackCellInitNum;
									}
									attributeAfterVal = session.minecraftSessionInfo.BackpackCellNum;
								}
								break;
							case EnumGoodsBelongsToType.SurvivorEquipment:
								{
									//幸存者装备
								}
								break;
							default:
								break;
						}
					}
					break;
				default:
					{
						session.Send(defCommand, req, new BaseResp { RespLevel = RespLevelEnum.Error, Msg = $"错误1：（原因：装备卸下中，暂不支持该属性【{mod_Items.modAttributeInfo_Convert.Id}:{mod_Items.modAttributeInfo_Convert.enumAttribute.ToString()}】加点）" });
						return;
					}
			}

			canCareGoodsInfo.GoodsItemId = equipmentInfo.GoodsItemId;
			canCareGoodsInfo.GoodsNum++;

			var goodsInfo = session.minecraftSessionInfo.goodsList.FirstOrDefault(m =>
			m.enumGoodsBelongsToType_Convert == canCareGoodsInfo.enumGoodsBelongsToType
			&& m.GoodsPosition == canCareGoodsInfo.GoodsPosition
			&& m.guid == canCareGoodsInfo.guid);
			if (goodsInfo == null)
			{
				goodsInfo = new GoodsModel
				{
					BelongsTo = (int)canCareGoodsInfo.enumGoodsBelongsToType,
					GoodsId = StringHelper.GetGuidStr(),
					GoodsItemId = canCareGoodsInfo.GoodsItemId,
					GoodsPosition = canCareGoodsInfo.GoodsPosition,
					guid = canCareGoodsInfo.guid,
					Num = canCareGoodsInfo.GoodsNum,
					PlayerId = session.minecraftSessionInfo.player.PlayerId,
					WastageValue = 100,
				};
				session.minecraftSessionInfo.goodsList.Add(goodsInfo);
			}
			else
			{
				goodsInfo.Num = canCareGoodsInfo.GoodsNum;
			}

			//session.minecraftSessionInfo.goodsList.Add(new GoodsModel
			//{
			//	BelongsTo = (int)canCareGoodsInfo.enumGoodsBelongsToType,
			//	GoodsId = equipmentInfo.GoodsId,
			//	GoodsItemId = equipmentInfo.GoodsItemId,
			//	GoodsPosition = canCareGoodsInfo.GoodsPosition,
			//	PlayerId = session.minecraftSessionInfo.player.PlayerId,
			//	WastageValue = equipmentInfo.WastageValue,
			//	guid = canCareGoodsInfo.guid,
			//	 Num = 
			//});

			//添加操作影响的positionOptList
			List<BackpackGoodsPositionOpt> positionOptList = new List<BackpackGoodsPositionOpt>();
			positionOptList.Add(new BackpackGoodsPositionOpt
			{
				enumGoodsBelongsToType = equipmentInfo.enumGoodsBelongsToType_Convert,
				GoodsPosition = equipmentInfo.GoodsPosition,
				guid = canCareGoodsInfo.guid,
			});
			positionOptList.Add(new BackpackGoodsPositionOpt
			{
				enumGoodsBelongsToType = canCareGoodsInfo.enumGoodsBelongsToType,
				GoodsPosition = canCareGoodsInfo.GoodsPosition,
				guid = canCareGoodsInfo.guid,
			});
			//组装响应数据
			List<BackpackCellInfo> posGoodsinfoList = new List<BackpackCellInfo>();
			//获取影响的位置列表（只有两个，一个背包，一个家具）
			positionOptList.ForEach(optItem =>
			{
				//找到受影响的物品位置信息
				posGoodsinfoList = session.minecraftSessionInfo.goodsList.Where(m => m.enumGoodsBelongsToType_Convert == optItem.enumGoodsBelongsToType && m.GoodsPosition == optItem.GoodsPosition && m.guid == req.guid).GetBackpackGoodsCellInfo();
			});
			//if (posGoodsinfoList.Count() == 1)
			//{
			//	posGoodsinfoList.Add(new BackpackCellInfo
			//	{
			//		enumGoodsBelongsToType = equipmentInfo.enumGoodsBelongsToType_Convert,
			//		GoodsItemId = equipmentInfo.GoodsItemId,
			//		GoodsList = new List<BackpackGoodsInfo>(),
			//		GoodsPosition = equipmentInfo.GoodsPosition,
			//		WastageValue = equipmentInfo.WastageValue,
			//		guid = req.guid
			//	});
			//}

			session.minecraftSessionInfo.goodsList.RemoveAll(m => m.Num <= 0);

			var resp = new EquipmentGoodsUnsnatchResp
			{
				posGoodsinfoList = posGoodsinfoList,
				enumAttribute = enumAttribute,
				attributeAfterVal = attributeAfterVal,
				enumEquipmentGoodsBelongsToType = req.enumGoodsBelongsToTypeSource,
				guid = req.guid
			};
			session.Send(defCommand, req, resp);
		}
	}
}
